package com.hpjpw.ido.controller;

import com.hpjpw.ido.config.IDoConfig;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @BelongsProject: RuoYi-IDo
 * @BelongsPackage: com.hpjpw.ido.controller
 * @Author: hpj
 * @CreateTime: 2021-03-18 20:31
 * @Description: 七牛云文件上传
 */
@RestController
@RequestMapping("/ido/qiniu")
public class QiNiuFileUploadController {
    @Autowired
    IDoConfig iDoConfig;
    @Autowired
    Auth qiNiuAuth;
    @Autowired
    private TokenService tokenService;

    @ApiOperation("七牛云的上传token")
    @GetMapping("/token")
    public AjaxResult getUploadToken(String suffix) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String bucket = iDoConfig.getBucket();

        String key = "userUpload/" +
                loginUser.getUser().getUserName() + "/" + //用户名
                DateUtils.datePath() + "/" +
                IdUtils.fastUUID() + "." + suffix;

        StringMap putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
        //putPolicy.put("mimeLimit", "image/*");
        putPolicy.put("insertOnly", 1);
        putPolicy.put("forceSaveKey", "true");
        putPolicy.put("saveKey",key);

        long expireSeconds = 3600;
        String upToken = qiNiuAuth.uploadToken(bucket, key, expireSeconds, putPolicy);
        AjaxResult success = AjaxResult.success();
        success.put("token", upToken);
        success.put("key", key);
        return success;
    }
}
